<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>子元素随父元素移动而移动</title>
		<style>
			/* css解决 页面多次点击时出现部分蓝色 */
			body {

				-webkit-user-select: none;
				-moz-user-select: none;
				-ms-user-select: none;
				user-select: none;

			}

			* {
				margin: 0;
				padding: 0;
				list-style: none;
			}

			#box {
				display: inline-block;
				position: relative;
				cursor: pointer;
			}

			.pop {
				padding: 7px 14px;
				background: #E0A800;
				border-radius: 6px;
				float: left;
			}

			.menu {
				position: absolute;
				top: 35px;
				left: 8px;
			}

			li {
				padding: 10px;
				background: #ccc;
			}

			.clearfix {
				clear: both;
			}
		</style>
	</head>
	<body>
		<div id="box" onclick="return false">
			<span class="pop">move</span>
			<div class="clearfix"></div>
			<ul class="menu">
				<li class="subMenu">111</li>
				<li class="subMenu">222</li>
				<li class="subMenu">333</li>
				<li class="subMenu">444</li>
			</ul>
		</div>
		<script src="../js/jquery.min.js"></script>
		<script>
			$('#box').mousedown(function(e) {
				var positionDiv = $(this).offset();
				var distenceX = e.pageX - positionDiv.left;
				var distenceY = e.pageY - positionDiv.top;

				$(document).mousemove(function(e) {
					var x = e.pageX - distenceX;
					var y = e.pageY - distenceY;
					if (x < 0) {
						x = 0;
					} else if (x > $(document).width() - $('#box').outerWidth(true)) {
						x = $(document).width() - $('#box').outerWidth(true);
					}
					if (y < 0) {
						y = 0;
					} else if (y > $(document).height() - $('#box').outerHeight(true)) {
						y = $(document).height() - $('#box').outerHeight(true);
					}
					$('#box').css({
						'left': x + 'px',
						'top': y + 'px'
					});
				});
				$(document).mouseup(function() {
					$(document).off('mousemove');
				});
			});
		</script>
	</body>
</html>
